package com.taichuan.selfcheck.mvp.presenter;


import android.content.Context;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;

import com.taichuan.mvp.base.MvpBasePresenter;
import com.taichuan.selfcheck.BaseApplication;
import com.taichuan.selfcheck.mvp.viewinterface.VideoTestInterface;
import com.taichuan.selfcheck.utils.DownLoadProgress;
import com.taichuan.tcutils.common.FileUtils;
import com.taichuan.tcutils.common.SDCardUtils;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static com.taichuan.selfcheck.ad.ADVideoPresenter.getVideoRootPath;

/**
 * Created by CamelLuo on 2018/6/21.
 */
public class VideoPresenter extends MvpBasePresenter<VideoTestInterface> {

    private final String TAG=VideoPresenter.class.getSimpleName();

    /**
     * 下载网络视频
     * @param videoUrl  视频地址
     * @param context   上下文
     */
    public void downLoadVideo(String videoUrl,Context context,boolean videoStatus){
       if(TextUtils.isEmpty(videoUrl)){
           getView().showMsg("视频地址不能为空");
       }else if(!videoUrl.endsWith("mp4")){
           getView().showMsg("视频地址不正确");
       }else if(!isConnectNet(context)){
           getView().showMsg("当前网络不可用");
       }else if(videoStatus){
           getView().showMessageDialog(videoUrl);
       }else{
           toDownVideo(videoUrl);
       }
    }

    public void toDownVideo(String videoUrl) {
        getView().pauseVideoPlay();
        getView().showLoading();
        Observable.just(videoUrl)
                .subscribeOn(Schedulers.io())
                .map(new Function<String, Integer>() {
                    @Override
                    public Integer apply(String s) throws Exception {
                        return download(s);
                    }
                })
                .delay(1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Integer successCacheCount) {
                        //成功缓存才执行更新操作
                        if (successCacheCount > 0) {
                            getView().hideLoading();
                            getView().playVideo();
                        }else{
                            getView().hideLoading();
                            getView().showMsg("下载失败，请检查视频地址是否正确");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        getView().hideLoading();
                        getView().showMsg(e.toString());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 下载网络文件
     * @param videoUrl  视频地址
     */
    private int download(String videoUrl) {
            int successCacheCount = 0;
                try {
                    Log.d(getClass().getSimpleName(), "onCacheLoad url : " + videoUrl);
                    String cacheName = getVideoRootPath()+"test.mp4";
                    File cacheFile = new File(cacheName);
                    long length = cacheFile.length();
                    long fileSize = 0;
                    fileSize = DownLoadProgress.get().execute(videoUrl, cacheFile);
                    Log.d(getClass().getSimpleName(), "onCacheLoad cachePath  :" + cacheName+"，fileSize: "+fileSize);
                    successCacheCount++;
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                }
                return  successCacheCount;

    }

    /**
     * 判断是否有网路连接
     * @param context  上下文
     * @return true为有网络连接
     */
  private boolean isConnectNet(Context context){
      ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo networkInfo=cm.getActiveNetworkInfo();
      return (networkInfo != null);
  }

    /**
     * 从外置内存卡指定路径（tc/test.mp4）复制文件到内置卡上
     */
  public void copyVideoFile(){
      String sdPath= SDCardUtils.getSecondaryStoragePath(BaseApplication.getApplication());
      File sdCardVideoFile=new File(sdPath+"/tc/","test.mp4");
      boolean isSdCard=SDCardUtils.hasSecondaryStorageSDCard(BaseApplication.getApplication());
      if(!isSdCard){
          getView().showMsg("加载失败，请检查是否正确插入SD卡");
      }else if(!sdCardVideoFile.exists()){
          Log.d(TAG,"sdCardVideoFile is not exists");
          getView().showMsg("加载失败，请检查视频文件是否存放正确");
      }else{
          getView().pauseVideoPlay();
          getView().showLoading();

          Observable.just(1)
                  .subscribeOn(Schedulers.io())
                  .map(new Function<Integer, Boolean>() {
                      @Override
                      public Boolean apply(Integer integer) throws Exception {
                          boolean isCopy=false;
                          try {
                              isCopy= FileUtils.copyFile(sdPath+"/tc/test.mp4",getVideoRootPath()+"test.mp4");
                              Log.d("aaa","复制文件: "+isCopy);
                          }catch (Exception e){
                              e.printStackTrace();
                          }
                          return isCopy;
                      }
                  })
                  .delay(3, TimeUnit.SECONDS)
                  .observeOn(AndroidSchedulers.mainThread())
                  .subscribe(new Observer<Boolean>() {
                      @Override
                      public void onSubscribe(Disposable d) {

                      }

                      @Override
                      public void onNext(Boolean isCopySuccess) {
                          if(isCopySuccess){
                              getView().hideLoading();
                              getView().playVideo();
                          }else{
                              getView().hideLoading();
                              getView().showMsg("加载失败，请检查视频文件是否存放正确");
                          }
                      }

                      @Override
                      public void onError(Throwable e) {
                          getView().hideLoading();
                          getView().showMsg(e.toString());
                      }

                      @Override
                      public void onComplete() {

                      }
                  });
      }
  }

    /**
     * 更改媒体音量
     * @param audio
     * @param KeyCode
     * @return
     */
  public boolean changeVolume(AudioManager audio,int KeyCode){
      switch (KeyCode){
          case KeyEvent.KEYCODE_2:
              //上调媒体音量
              audio.adjustStreamVolume(
                      AudioManager.STREAM_MUSIC,
                      AudioManager.ADJUST_RAISE,
                      AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
              return true;
          case KeyEvent.KEYCODE_8:
              //下调媒体音量
              audio.adjustStreamVolume(
                      AudioManager.STREAM_MUSIC,
                      AudioManager.ADJUST_LOWER,
                      AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
              return true;
      }
      return false;
  }
}
